package com.example.starter.mybatis.handler;

import cn.hutool.core.lang.ClassScanner;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.example.starter.mybatis.base.MultiTenant;
import com.example.starter.mybatis.configure.MybatisProperties;
import com.example.starter.webmvc.util.WebUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 王令
 * @since 2022/9/30 22:11
 */
public class ExampleTenantLineHandler implements TenantLineHandler {

    private static final List<String> cache = new ArrayList<>();

    public ExampleTenantLineHandler(MybatisProperties properties) {
        Set<Class<?>> clazz = ClassScanner.scanPackageBySuper(properties.getMultiTenant().getBasePackage(), MultiTenant.class);
        for (Class<?> aClass : clazz) {
            final TableName tableName = AnnotationUtils.findAnnotation(aClass, TableName.class);
            if (tableName != null) {
                cache.add(tableName.value());
            }
        }
    }


    @Override
    public Expression getTenantId() {
        return new StringValue(WebUtil.getTenantId());
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return !cache.contains(tableName);
    }

}
